var pageSize = 5;

//create data store
var dataStore = new Ext.data.Store(
    {
        proxy: new Ext.data.HttpProxy
        (
            { url: base_url + '/articles/ajax-fetch-articles/' }
        ),

        reader: new Ext.data.JsonReader
        (
            { root: 'rows', totalProperty: 'count', id: 'id' },
            [
                { name: 'id', mapping: 'id' },
                { name: 'title', mapping: 'title' },
                { name: 'author', mapping: 'author' },
                { name: 'category', mapping: 'category' }
            ]
        ),
    }
);

// create the Grid
var grid = new Ext.grid.GridPanel({
    store: dataStore,
    columns: 
    [
        { id:'id', header: "Id", width: 50, sortable: true, dataIndex: 'id'},
        { id:'title', header: "Title", width: 150, sortable: true, dataIndex: 'title'},
        { id:'author', header: "Author", width: 150, renderer: renderName, sortable: true, dataIndex: 'author'},
        { id:'category', header: "Category", width: 150, renderer: renderName, sortable: true, dataIndex: 'category'},
        { header: 'Edit', width:50, renderer: renderEdit, align: 'center', sortable: false, dataIndex: 'id'},
        { header: 'Delete', width:50, renderer: renderDelete, align: 'center', sortable: false, dataIndex: 'id'},
    ],
    stripeRows: true,
    height:300,
    width:610,
    title:'Articles Grid',
	bbar: new Ext.PagingToolbar({
	    pageSize:       pageSize,
	    store:          dataStore,
	    displayInfo:    true,
	    displayMsg:     'Results {0} - {1} of {2}',
	    emptyMsg:       'No results'
	}),    
});

function renderName(value, p, record) {
    return value['name'];
}

function renderEdit(value, p, record) {
    return String.format('<img src="images/common/fico_modify.gif" style="margin-left: 2px; cursor: pointer" onclick="javascript:editRow({0})" />', value );
}

function renderDelete(value, p, record) {
    return String.format('<img src="images/common/fico_trash.gif" style="margin-left: 2px; cursor: pointer" onclick="javascript:deleteRow({0})" />', value );
}
    
function editRow(id) {
    window.location.href = base_url + '/articles/edit/id/' + id;
}

function deleteRow(id) {
    window.location.href = base_url + '/articles/delete/id/' + id;
}
       
function reloadGrid(author_id, category_id)
{
    //send request and render the grid
    dataStore.load({
    	params: {
    		start: 0,
    		limit: pageSize,
    		author_id: author_id,
    		category_id: category_id
    	}
    });
    grid.render('article-grid');
}